<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodItem :good="good" />
      </li>
    </ul>
  </div>
  <!-- 上来加载更多组件 -->
  <XtxInfiniteLoad
    :isLoading="isLoading"
    :isFinished="isFinished"
    @load="onLoad"
  />
</template>

<script>
import { findSubCategoryGoods } from '@/api/category.js'
import GoodItem from './goods-item.vue'

import { ref, inject, watch } from 'vue'
import { useRoute } from 'vue-router'
// 抽离列表渲染的逻辑
function useList (params) {
  const route = useRoute()
  const goodList = ref([])
  const requestParams = {
    page: 0,
    pageSize: 20,
    categoryId: route.params.id,
    sortField: null, // 排序类别
    attrs: [], // 商品属性
    brandId: null // 品牌名称
  }
  // 实现和是哪个拉加载更多
  const isLoading = ref(false)

  const isFinished = ref(false)
  const filterParams = inject('filterParams')
  // 下拉加载更多的回调函数
  const onLoad = async () => {
    isLoading.value = true
    requestParams.page++
    const { result: { items, counts } } = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
    console.log('列表', items, counts)
    goodList.value.push(...items)
    isLoading.value = false
    if (goodList.value.length === counts) {
      isFinished.value = true
    }
  }
  return { goodList, isLoading, requestParams, isFinished, onLoad }
}
export default {
  components: {
    GoodItem
  },
  setup () {
    // 获取过滤条件的数据
    const filterParams = inject('filterParams')
    const { goodList, isLoading, isFinished, requestParams, onLoad } = useList(filterParams)
    // 监控筛选条件的变化重新刷新列表
    watch(() => filterParams.value, () => {
      //  重置列表 =>删除列表数据
      goodList.value = []
      requestParams.page = 0
      isLoading.value = false
      isFinished.value = false
      // getGoodList()
    }, {
      deep: true
    }
    )
    // const getGoodList = async () => {
    //   const { result: { items } } = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
    //   console.log('列表', items)S
    //   goodList.value = items
    // }

    // onMounted(() => {
    //   getGoodList()
    // })
    return { goodList, isLoading, isFinished, onLoad }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
